UNHCR Population statistics Database • Country Focus

Forcible Displacement Statistics

Intro

Seven Key Questions

addressed through predefined crafted static charts

  1. What is the share of Forcibly Displaced People among total Migrants?

  2. How the different Categories of Forcibly Displaced People are evolving over time?

  3. What are the main Countries of Origin of Forcibly Displaced People?

  4. What are the Demographics profiles of Forcibly Displaced People in relation with the host population?

  5. What are the trends in term of Solutions in this Country?

  6. Is the asylum Processing capacity in relation with the demand?

  7. If happening, what is the evolution of a country as a displacement Source?


Charts can easily be copied as an image as is, or adjusted using a reproducible source code in R statistical language.

For instance, you can change the title from a key question to a key message or add annotations to support data storytelling.


The resulting charts can be embedded in reports, fact-sheets, social media or presentations to accompany a narrative / campaign. More information on Forcible Displacement Statistic is available with UNHCR here and through International Statistical Recommendations on refugee / asylum seekers and Internally Displaced People

World

lastyear <- 2021

Categories

#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(   Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = " ",
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin

#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
data <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter( Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(data, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin ","" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics

demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter( Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in" ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People" ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution

#Prepare data
Solution <- solutions_long.asy %>%
  filter(Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = "",
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing

linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(Year == lastyear  ) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(Year == lastyear) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(Year == lastyear ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decisionGlobal.html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decisionGlobal.html"),
                 paste0(getwd(),"/decision/decisionGlobal.png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)

Source

lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries source of Forcibly Displaced People "),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

America

Regional Overview

thisbureau <- "Americas"
ctr <- selectedctr  %>%
  filter( UNHCRBureau == thisbureau) %>%
  select(CountryAsylumName)
# as.character(ctr$CountryAsylumName)
 
#  "Dominican Republic"                 "Costa Rica"                        
#  "El Salvador"                        "Guatemala"                         
#  "Honduras"                           "Mexico"                            
#  "Panama"                             "Canada"                            
#  "United States of America"           "Argentina"                         
#  "Brazil"                             "Chile"                             
# "Colombia"                           "Ecuador"                           
#  "Peru"                               "Venezuela (Bolivarian Republic of)"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(UNHCRBureau == thisbureau  & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
data <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(data, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thisbureau , "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(UNHCRBureau == thisbureau  & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thisbureau  ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thisbureau  ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(UNHCRBureau == thisbureau  & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   ) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thisbureau ,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thisbureau ,".html"),
                 paste0(getwd(),"/decision/decision", thisbureau ,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryOriginCode" = "iso_3"))  %>%
 filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Source Countries hosting Forcibly Displaced People from ",thisbureau  ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Northern America

Canada
thiscountry <- "Canada"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

USA
thiscountry <- "United States of America"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}
 Gender disaggregation is not available for all of the 1,338,835 persons inUnited States of America
Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Mexico
thiscountry <- "Mexico"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Central America

Guatemala
thiscountry <- "Guatemala"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}
 Gender disaggregation is not available for all of the 113,975 persons inGuatemala
Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

El Salvador
thiscountry <- "El Salvador"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Honduras
thiscountry <- "Honduras"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Costa Rica
thiscountry <- "Costa Rica"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}
 Gender disaggregation is not available for all of the 121,941 persons inCosta Rica
Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Panama
thiscountry <- "Panama"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}
 Gender disaggregation is not available for all of the 134,391 persons inPanama
Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Caribean

Dominican Republic
thiscountry <- "Dominican Republic"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Southern America

Argentina
thiscountry <- "Argentina"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Brazil
thiscountry <- "Brazil"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}
 Gender disaggregation is not available for all of the 425,521 persons inBrazil
Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Chile
thiscountry <- "Chile"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Colombia
thiscountry <- "Colombia"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Ecuador
thiscountry <- "Ecuador"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Peru
thiscountry <- "Peru"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}
 Gender disaggregation is not available for all of the 1,557,216 persons inPeru
Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Venezuela
thiscountry <- "Venezuela (Bolivarian Republic of)"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Asia

Regional Overview

thisbureau <- "Asia"
ctr <- selectedctr  %>%
  filter( UNHCRBureau == thisbureau) %>%
  select(CountryAsylumName)
#as.character(ctr$CountryAsylumName)
#  "Australia"                  "Uzbekistan"                 "China"                     
#  "Cambodia"                   "Malaysia"                   "Myanmar"                   
#  "Philippines"                "Thailand"                   "Afghanistan"               
#  "Bangladesh"                 "India"                      "Iran (Islamic Republic of)"
#  "Pakistan"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(UNHCRBureau == thisbureau  & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
data <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(data, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thisbureau , "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(UNHCRBureau == thisbureau  & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thisbureau  ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thisbureau  ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(UNHCRBureau == thisbureau  & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   ) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thisbureau ,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thisbureau ,".html"),
                 paste0(getwd(),"/decision/decision", thisbureau ,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryOriginCode" = "iso_3"))  %>%
 filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Source Countries hosting Forcibly Displaced People from ",thisbureau  ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

East Asia and the Pacific

Australia
thiscountry <- "Australia"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}
 Gender disaggregation is not available for all of the 138,260 persons inAustralia
Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

China
thiscountry <- "China"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

South Asia

India
thiscountry <- "India"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

South East Asia

Thailand
thiscountry <- "Thailand"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Bangladesh
thiscountry <- "Bangladesh"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Myanmar
thiscountry <- "Myanmar"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Philippines
thiscountry <- "Philippines"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Cambodia
thiscountry <- "Cambodia"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}
 Gender disaggregation is not available for all of the 57,456 persons inCambodia
Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Malaysia
thiscountry <- "Malaysia"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

South West Asia

Iran
thiscountry <- "Iran (Islamic Republic of)"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}
 Gender disaggregation is not available for all of the 800,064 persons inIran (Islamic Republic of)
Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Pakistan
thiscountry <- "Pakistan"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Afghanistan
thiscountry <- "Afghanistan"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Europe

Regional Overview

thisbureau <- "Europe"
ctr <- selectedctr  %>%
  filter( UNHCRBureau == thisbureau) %>%
  select(CountryAsylumName)
#as.character(ctr$CountryAsylumName)
#  [1] "Russian Federation"                                  
#  [2] "Ukraine"                                             
#  [3] "Estonia"                                             
#  [4] "Latvia"                                              
#  [5] "Sweden"                                              
#  [6] "United Kingdom of Great Britain and Northern Ireland"
#  [7] "Bosnia and Herzegovina"                              
#  [8] "Greece"                                              
#  [9] "Italy"                                               
# [10] "Serbia"                                              
# [11] "Spain"                                               
# [12] "Azerbaijan"                                          
# [13] "Georgia"                                             
# [14] "Turkey"                                              
# [15] "Austria"                                             
# [16] "Belgium"                                             
# [17] "Germany"                                             
# [18] "Netherlands"                                         
# [19] "Switzerland"                                         
# [20] "France"                                              
# [21] "Norway" 
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(UNHCRBureau == thisbureau  & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
data <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(data, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thisbureau , "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(UNHCRBureau == thisbureau  & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thisbureau  ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thisbureau  ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(UNHCRBureau == thisbureau  & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   ) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thisbureau ,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thisbureau ,".html"),
                 paste0(getwd(),"/decision/decision", thisbureau ,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryOriginCode" = "iso_3"))  %>%
 filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Source Countries hosting Forcibly Displaced People from ",thisbureau  ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Western Europe

UK
thiscountry <- "United Kingdom of Great Britain and Northern Ireland"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Germany
thiscountry <- "Germany"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

France
thiscountry <- "France"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Northern Europe

Latvia
thiscountry <- "Latvia"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}
 Gender disaggregation is not available for all of the 209,877 persons inLatvia
Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Estonia
thiscountry <- "Estonia"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}
 Gender disaggregation is not available for all of the 73,496 persons inEstonia
Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Norway
thiscountry <- "Norway"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Sweden
thiscountry <- "Sweden"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Southern Europe

Italy
thiscountry <- "Italy"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}
 Gender disaggregation is not available for all of the 184,918 persons inItaly
Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Spain
thiscountry <- "Spain"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Greece
thiscountry <- "Greece"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Eastern Europe

Turkey
thiscountry <- "Turkey"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Georgia
thiscountry <- "Georgia"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Russian Federation
thiscountry <- "Russian Federation"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}
 Gender disaggregation is not available for all of the 81,238 persons inRussian Federation
Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

MENA

Regional Overview

thisbureau <- "MENA"
ctr <- selectedctr  %>%
  filter( UNHCRBureau == thisbureau) %>%
  select(CountryAsylumName)
#as.character(ctr$CountryAsylumName)

 # [1] "Algeria"              "Egypt"                "Libya"                "Mauritania"          
 # [5] "Iraq"                 "Jordan"               "Kuwait"               "Lebanon"             
 # [9] "Saudi Arabia"         "Syrian Arab Republic" "Yemen" 
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(UNHCRBureau == thisbureau  & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
data <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(data, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thisbureau , "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(UNHCRBureau == thisbureau  & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thisbureau  ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thisbureau  ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(UNHCRBureau == thisbureau  & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   ) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thisbureau ,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thisbureau ,".html"),
                 paste0(getwd(),"/decision/decision", thisbureau ,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryOriginCode" = "iso_3"))  %>%
 filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Source Countries hosting Forcibly Displaced People from ",thisbureau  ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Northern Africa

Algeria
thiscountry <- "Algeria"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Egypt
thiscountry <- "Egypt"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Middle East

Jordan
thiscountry <- "Jordan"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Syria
thiscountry <- "Syrian Arab Republic"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Western Africa

Regional Overview

thisbureau <- "WestAfrica"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(UNHCRBureau == thisbureau  & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
data <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(data, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thisbureau , "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(UNHCRBureau == thisbureau  & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thisbureau  ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thisbureau  ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(UNHCRBureau == thisbureau  & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   ) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thisbureau ,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thisbureau ,".html"),
                 paste0(getwd(),"/decision/decision", thisbureau ,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryOriginCode" = "iso_3"))  %>%
 filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Source Countries hosting Forcibly Displaced People from ",thisbureau  ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Central Africa

Cameroon
thiscountry <- "Cameroon"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Chad
thiscountry <- "Chad"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Central African Republic
thiscountry <- "Central African Republic"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

West Africa

Burkina Faso
thiscountry <- "Burkina Faso"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Mali
thiscountry <- "Mali"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Niger
thiscountry <- "Niger"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Nigeria
thiscountry <- "Nigeria"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Eastern Africa

Regional Overview

thisbureau <- "EastAfrica"
ctr <- selectedctr  %>%
  filter( UNHCRBureau == thisbureau) %>%
  select(CountryAsylumName)
#as.character(ctr$CountryAsylumName)
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(UNHCRBureau == thisbureau  & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
data <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(data, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thisbureau , "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(UNHCRBureau == thisbureau  & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thisbureau  ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thisbureau  ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(UNHCRBureau == thisbureau  & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   ) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thisbureau ,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thisbureau ,".html"),
                 paste0(getwd(),"/decision/decision", thisbureau ,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryOriginCode" = "iso_3"))  %>%
 filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Source Countries hosting Forcibly Displaced People from ",thisbureau  ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Great Lakes

Burundi
thiscountry <- "Burundi"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Rwanda
thiscountry <- "Rwanda"

East and Horn

Ethiopia
thiscountry <- "Ethiopia"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Kenya
thiscountry <- "Kenya"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Somalia
thiscountry <- "Somalia"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

##### South Sudan{.tabset}

thiscountry <- "South Sudan"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

##### Uganda{.tabset}

thiscountry <- "Uganda"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Tanzania
thiscountry <- "United Republic of Tanzania"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Zambia
thiscountry <- "Zambia"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Sudan
thiscountry <- "Sudan"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Southern Africa

Regional Overview

thisbureau <- "SouthAfrica"
ctr <- selectedctr  %>%
  filter( UNHCRBureau == thisbureau) %>%
  select(CountryAsylumName)
#as.character(ctr$CountryAsylumName)
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(UNHCRBureau == thisbureau  & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
data <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(data, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thisbureau , "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(UNHCRBureau == thisbureau  & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thisbureau  ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thisbureau  ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(UNHCRBureau == thisbureau  & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thisbureau ),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   ) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  ) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thisbureau ,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thisbureau ,".html"),
                 paste0(getwd(),"/decision/decision", thisbureau ,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryOriginCode" = "iso_3"))  %>%
 filter(UNHCRBureau == thisbureau  & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Source Countries hosting Forcibly Displaced People from ",thisbureau  ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Southern Africa

South Africa
thiscountry <- "South Africa"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Malawi
thiscountry <- "Malawi"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Mozambique
thiscountry <- "Mozambique"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Angola
thiscountry <- "Angola"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Middle Africa

Democratic Republic of the Congo
thiscountry <- "Democratic Republic of the Congo"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Congo
thiscountry <- "Congo"
Categories
#Prepare data
Categories <- end_year_population_totals_long.asy %>%
  filter(CountryAsylumName  == thiscountry & 
                 Year > (lastyear - 5) ) %>%
  group_by(Year, Population.type.label.short ) %>%
  summarise(Value2 = sum(Value) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))

ncat <- ifelse( nlevels(as.factor(Categories$Population.type.label.short)) %in% c(2,4), 2,3)
#levels(as.factor(end_year_population_totals_long.asy$Population.type.label.short))
Categories$Population.type.label.short <- factor(Categories$Population.type.label.short,
                                                 levels = c("Refugees","Asylum-seekers","Venezuelans Abroad",
                                                            "IDPs","Stateless Persons", "Others of Concern")) 


#Make plot
ggplot(Categories, aes(x = Year, 
                       y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc"
           ) + # here we configure that it will be bar chart
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear)) +
  facet_wrap( vars(Population.type.label.short ), ncol = ncat) +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "How the different Categories of Forcibly Displaced People are evolving over time?",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Origin
#Prepare data2
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
## Loading the stat tables
Origin <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
  filter(CountryAsylumName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryOriginName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Origin, aes(x = reorder(CountryOriginName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryOriginName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries of Origin hosted in ",thiscountry, "" ),
       subtitle = paste0("Data as of ",lastyear), 
       x = " ",
       y = "# of Forcibly displaced people",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

Demographics
demographics1 <- demographics %>%
                   dplyr::left_join( unhcrdatapackage::reference %>% 
                                       select(UNHCRBureau, iso_3),  
                                     by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(CountryAsylumName  == thiscountry & Year == lastyear-1) %>%
                  mutate ( totGen = FemaleTotal +MaleTotal,
                           totbreak = Female04 + Female511 + Female1217 + Female1859 + Female60ormore + FemaleUnknown +
                             Male04 + Male511 + Male1217 + Male1859 + Male60ormore + MaleUnknown,
                           hasbreak = ifelse(Total - totGen == 0, "yes", "no" ))

tot <- format( sum(demographics1$Total) ,  big.mark=",")
totprop <-   format( round( sum(demographics1$totGen) / 
    sum(demographics1$Total )  *100,1),  big.mark=",")  

if (totprop == 0 ) {
  cat(paste0(" Gender disaggregation is not available for all of the ",tot, " persons in", thiscountry ))
  
} else {
#names(demographics)
pyramid <-  demographics1[ demographics1$Year == max(demographics1$Year),
                          c(
                              "Female04",
                              "Female511",
                              "Female1217",
                              "Female1859",
                              "Female60ormore",
                              "FemaleUnknown",
                             # "FemaleTotal",
                              "Male04",
                              "Male511",
                              "Male1217",
                              "Male1859",
                              "Male60ormore",
                              "MaleUnknown"#,
                             # "MaleTotal"       
                             )]  

pyramid2 <- data.frame(lapply(pyramid, function(x) { as.numeric( gsub("NA", "0", x)) })) %>%
  pivot_longer(
    cols = Female04:MaleUnknown,
    names_to = "Class",
    values_to = "Sum",
    values_drop_na = TRUE
  ) 

pyramid3 <- as.data.frame(aggregate(pyramid2$Sum,
                                          by = list(pyramid2$Class#, pyramid2$REGION_UN
                                                    ),
                                          sum))
names(pyramid3)[1] <- "Class"
names(pyramid3)[2] <- "Count"

pyramid3 <- pyramid3 %>% 
  mutate(gender = case_when(str_detect(Class, "Male") ~ "Male",
                            str_detect(Class, "Female") ~ "Female")) %>% 
  mutate(age = case_when(str_detect(Class, "04") ~ "0-4",
                         str_detect(Class, "511") ~ "5-11",
                         str_detect(Class, "1217") ~ "12-17",
                         str_detect(Class, "1859") ~ "18-59",
                         str_detect(Class, "60") ~ "60+",
                         str_detect(Class, "Unknown") ~ "Unknown")) 

pyramid3$pc <- pyramid3$Count / sum(pyramid3$Count) * 100
pyramid3$age <- factor(pyramid3$age, levels = c("0-4", "5-11",  "12-17",  "18-59", "60+", "Unknown"))

pyramidplot <- ggplot(pyramid3, aes(x = age, 
                     fill = gender,
                      y = ifelse(test = gender == "Female",
                            yes = -pc, no = pc)) ) + 
  geom_bar(stat = "identity") +
  geom_label(aes(x = age,
                 y = ifelse(test = gender == "Female",
                            yes = -pc -5 , no = pc),
                label =  paste0(format(round(pc, 1),  big.mark=","),"%") 
                ),
             hjust = 0,
             vjust = 0.5,
             colour = "black",
             fill = NA,
             label.size = NA,
             family = "Lato",
             size = 5) +
  scale_y_continuous(labels = abs, limits = max(pyramid3$pc) * c(-1,1)) +
  labs(title = paste0("Population Pyramid for Forcibly Displaced People in", thiscountry ),
       subtitle = paste0(" Gender disaggregation is available for ", totprop, " % of the ",tot, " persons in this country" ),
       x = "", 
       y = "Percent of population",
       caption =  "Source: UNHCR Population Statistics as of end 2020") +
  scale_colour_manual(values = c("#126db4","#01ab91"), # based on Asia Report
                      aesthetics = c("colour", "fill")) +
  coord_flip()+
  unhcRstyle::unhcr_theme(base_size = 14) +
   theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
            panel.grid.major.y = element_blank())

pyramidplot
}

Solution
#Prepare data
Solution <- solutions_long.asy %>%
  filter(CountryAsylumName  == thiscountry & Year > (lastyear - 10)  ) %>%
  group_by(Year, Solution.type.label ) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate(Year = as.integer(Year) ) %>%
  mutate( valabel = scales::label_number_si()(Value2))


ncat <- ifelse( nlevels(as.factor(Solution$Solution.type.label)) %in% c(2,4), 2,3)
#levels(as.factor(solutions_long.asy$Solution.type.label))
Solution$Solution.type.label <- factor(Solution$Solution.type.label,
                                                 levels = c("Naturalisation",  "Resettlement arrivals",
                                                            "Refugee returns","IDP returns" )) 

#Make plot
ggplot(Solution, aes(x = Year, y = Value2  )) + 
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc" ) + # here we configure that it will be bar chart
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  #xlim(c(lastyear-5, lastyear+1)) +
  facet_wrap( vars(Solution.type.label ), ncol = ncat) +
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.y  = element_line(color = "#cbcbcb"), 
        panel.grid.major.x  = element_blank(), 
        panel.grid.minor = element_blank()) + ### changing grid line that should appear
  ## and the chart labels
  labs(title = "Recorded Solutions",
       subtitle = paste0(thiscountry),
       x = "",
       y = "",
       caption = "Source: UNHCR.org/refugee-statistics ")

Processing
linksDecision.Ori.Procedure <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear  & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  mutate(CountryOriginName = forcats::fct_lump_prop(CountryOriginName, prop = .01, w = Value)) %>% 
  mutate(CountryOriginName = str_replace(CountryOriginName, " \\(Bolivarian Republic of\\)", "")) %>% 
  ## Calculate grouped value for Origin to procedure..
  group_by(CountryOriginName, ProcedureName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = CountryOriginName) %>%
  rename(target = ProcedureName) 

linksDecision.Procedure.Type <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(ProcedureName, DecisionTypeName ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = ProcedureName) %>%
  rename(target = DecisionTypeName) 

linksDecision.Type.Output <- asylum_decisions_long %>%
  ## Add reference for the filters
  dplyr::left_join( unhcrdatapackage::reference %>% 
                      select(coa_region = `UNHCRBureau`, iso_3),  by = c("CountryAsylumCode" = "iso_3")) %>% 
  filter(coa_region == thisbureau & Year == lastyear   & CountryAsylumName  == thiscountry) %>% 
  ## Group small records under other
  ## Calculate grouped value for Origin to procedure..
  group_by(DecisionTypeName,Decision.output ) %>%
  summarise(value = sum(Value) ) %>%
  ## Rename variable
  rename(source = DecisionTypeName) %>%
  rename(target = Decision.output)

 

linksallDecision <- rbind(linksDecision.Ori.Procedure,
                  linksDecision.Procedure.Type,
                  linksDecision.Type.Output )



# From these flows we need to create a node data frame: it lists every entities involved in the flow
nodesDecision <- data.frame(
  name=c(as.character(linksallDecision$source), 
         as.character(linksallDecision$target)) %>% unique()
)

# With networkD3, connection must be provided using id, not using real name like in the links dataframe.. So we need to reformat it.
linksallDecision$IDsource <- match(linksallDecision$source, nodesDecision$name)-1 
linksallDecision$IDtarget <- match(linksallDecision$target, nodesDecision$name)-1

# Make the Network
p <- networkD3::sankeyNetwork(Links = linksallDecision, 
                              Nodes = nodesDecision,
                              Source = "IDsource", 
                              Target = "IDtarget",
                              Value = "value", 
                              NodeID = "name", 
                              # LinkGroup    character string specifying the groups in the Links. Used to color the links in the network.
                              sinksRight=FALSE) ##  If TRUE, the last nodes are moved to the right border of the plot.
# you save it as an html
networkD3::saveNetwork(p, paste0(getwd(),"/decision/decision", thiscountry,".html"))

# you convert it as png -- Need first webshot::install_phantomjs()
webshot::webshot(paste0(getwd(),"/decision/decision", thiscountry,".html"),
                 paste0(getwd(),"/decision/decision", thiscountry,".png"),
                 vwidth = 800, vheight = 500)

#getwd()
#![ ](graph/decision.png)
Source
lastyear <- max(unhcrdatapackage::end_year_population_totals_long$Year)
Source <- dplyr::left_join( x= unhcrdatapackage::end_year_population_totals_long, 
                                                     y= unhcrdatapackage::reference, 
                                                     by = c("CountryAsylumCode" = "iso_3"))  %>%
 filter(CountryOriginName  == thiscountry & Year == lastyear) %>%   
  mutate(CountryAsylumName = str_replace(CountryAsylumName, " \\(Bolivarian Republic of\\)", ""),
        CountryAsylumName = str_replace(CountryAsylumName, "Iran \\(Islamic Republic of\\)", "Iran"),
        CountryAsylumName = str_replace(CountryAsylumName, "United States of America", "USA"),
        CountryAsylumName = str_replace(CountryAsylumName, "United Kingdom of Great Britain and Northern Ireland", "UK")) %>% 
  group_by( CountryAsylumName, SUBREGION) %>%
  summarise(Value2 = sum(Value) )  %>%
  mutate( Value3 =  scales::label_number_si()(Value2)) %>%
  arrange(desc(Value2)) %>%
  head(10)

#Make plot
ggplot(Source, aes(x = reorder(CountryAsylumName, Value2), ## Reordering country by Value
                           y = Value2)) +
  geom_bar(stat = "identity", 
           position = "identity", 
           fill = "#0072bc") + # here we configure that it will be bar chart+
  geom_label(aes(x = CountryAsylumName, y = Value2, 
                #label =  format(round(Value2, -3),  big.mark=",")), 
                label =  Value3), 
             hjust = 1, 
             vjust = 0.5, 
             colour = "white", 
             fill = NA, 
             label.size = NA, 
             family = "Lato", 
             size = 6) +
  geom_hline(yintercept = 0, size = 1, colour = "#333333") +
  coord_flip() + # Add `coord_flip()` to make your vertical bars horizontal:
  ## and the chart labels
  labs(title = paste0("Top 10 Countries hosting Forcibly Displaced People from ",thiscountry ),
       subtitle = paste0("Data as of ",lastyear), 
       x = "",
       y = "",
       caption = "UNHCR https://www.unhcr.org/refugee-statistics/") +
  #scale_y_continuous( label = unhcRstyle::format_si()) + ## Format axis number
  scale_y_continuous( label = scales::label_number_si()) + ## Format axis number
  geom_hline(yintercept = 0, size = 1.1, colour = "#333333") +
  unhcRstyle::unhcr_theme(base_size = 14)  + ## Insert UNHCR Style
  theme(panel.grid.major.x = element_line(color = "#cbcbcb"), 
        panel.grid.major.y = element_blank()) ### changing grid line that should appear

 

UnhcrDataPackage - Re-usable/adjustable Source codes for Country Focused Statistical Charts are available Here.

Feel free to share comments through issues ticket